﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Poker24Demo
{
    public class PlayPoker
    {
        public string[] Pokers = new string[13] {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};

        private string pokerA, pokerB, pokerC, pokerD = null;
        private DataTable dataTable = new DataTable();
        private Poker24 p24 = new Poker24();

        public string Play() {
            

            pokerA = GetRandomPoker();
            pokerB = GetRandomPoker();
            pokerC = GetRandomPoker();
            pokerD = GetRandomPoker();

            return $"{pokerA} {pokerB} {pokerC} {pokerD}";
        }

        private string ConvertPoker(string poker) {

            string res = null;

            switch (poker) {
                case "A":
                    res = "1";
                    break;
                case "J":
                    res = "1";
                    break;
                case "Q":
                    res = "1";
                    break;
                case "K":
                    res = "1";
                    break;
                default:
                    res = poker;
                    break;
            }

            return res;
        }

        private string GetRandomPoker() {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            int iSeed = BitConverter.ToInt32(buffer, 0);
            Random ran = new Random(iSeed);

            int index = ran.Next(0, Pokers.Length);
            return Pokers[index];
        }

        public string InputFormula() {
            string formula = string.Empty;

            Boolean isComplete = false;

            while (!isComplete) {
                //ConsoleKeyInfo key = Console.ReadKey();
                //if (key.Key == ConsoleKey.Enter)
                //{
                //    isComplete = true;
                //    break;
                //}
                //formula += key.KeyChar;
                formula = Console.ReadLine();
                isComplete = true;

            }
            return formula;
        }

        public Boolean CheckFormula(string formula) {

            try {
                var res = dataTable.Compute(formula, null).ToString();
                return res == "24";
            }
            catch (Exception err) {
                return false;
            }

            
        }

        public List<string> PokerResult() {
            try {
                p24.DealFourCards(ConvertPoker(pokerA), ConvertPoker(pokerB), ConvertPoker(pokerC), ConvertPoker(pokerD));
                var res = p24.Calc24();
                if (res == null || res.Count == 0) return null;

                return res.Select(x => $"{x.Formula()} = 24").ToList();
            }
            catch (Exception err) {
                return null;
            }
            

        }
    }
}
